package com.gome.ai.aiparter.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import okhttp3.*;

import java.io.*;



@RestController
public class BaiduController {

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Value("${baidu-api.client_id}")
    String client_id;
    @Value("${baidu-api.client_secret}")
    String client_secret;

    @GetMapping("/token")
    public String getToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(String.format("https://aip.baidubce.com/oauth/2.0/token?client_id=%s&client_secret=%s&grant_type=client_credentials",client_id,client_secret))
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSON.parseObject(response.body().string()).getString("access_token");
    }
}